import {removeRule, rule} from '@/services/ant-design-pro/api';
import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProTable,
} from '@ant-design/pro-components';
import {useRequest} from '@umijs/max';
import type {PopconfirmProps} from 'antd';
import {Button, Drawer, Input, message, Popconfirm} from 'antd';
import {QuestionCircleOutlined} from '@ant-design/icons';
import React, {useCallback, useRef, useState} from 'react';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import {
  addInterfaceInfoUsingPost, deleteInterfaceInfoUsingPost, interfaceDownUsingPost, interfaceUpUsingPost,
  listInterfaceInfoByPageUsingPost, updateInterfaceInfoUsingPost
} from "@/services/api_open_platform/interfaceInfoController";
import CreateModal from "@/pages/admin/InterfaceInfo/components/CreateModal";
import UpdateModal from "@/pages/admin/InterfaceInfo/components/UpdateModal";

const TableList: React.FC = () => {
  const [selectedRowsState, setSelectedRows] = useState<API.RuleListItem[]>([]);
  const actionRef = useRef<ActionType | null>(null);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<API.InterfaceInfo>();
  // 控制模态框显示的状态
  const [createModalOpen, setCreateModalOpen] = useState(false);
  const [updateModalOpen, setUpdateModalOpen] = useState(false);
  // 处理模态框开关的方法
  const handleModalOpen = (open: boolean) => {
    setCreateModalOpen(open);
  };
  const handleUpdateModalOpen = (open: boolean) => {
    setUpdateModalOpen(open);
  };
  // 把参数的类型改成InterfaceInfo
  const handleAdd = async (fields: API.InterfaceInfoAddRequest) => {
    const hide = message.loading('正在添加');
    try {
      // 把addRule改成addInterfaceInfoUsingPOST
      const res = await addInterfaceInfoUsingPost({
        ...fields,
      });
      hide();
      if (res.code === 0) {
        message.success('创建成功');
        // 创建成功就关闭这个模态框
        handleModalOpen(false);
      } else {
        // 否则提示'创建失败' + 报错信息
        message.error('创建失败，' + res.message);
      }
      return true;
    } catch (error: any) {
      hide();
      // 否则提示'创建失败' + 报错信息
      message.error('创建失败，' + error.message);
      return false;
    }
  };

  const handleUpdate = async (fields: API.InterfaceInfo) => {
    if (!currentRow) {
      return;
    }
    const hide = message.loading('修改过程中');
    try {
      const res = await updateInterfaceInfoUsingPost({
        id: currentRow.id,
        ...fields,
      });
      hide();
      if (res.code === 0) {
        message.success("修改成功");
        handleUpdateModalOpen(false);
      } else {
        message.success(res.message);
      }
    } catch (e: any) {
      hide();
      message.error("操作失败，" + e.message);
      return false;
    }
  }

  const handleDelete = async (e: React.MouseEvent, record: API.InterfaceInfo) => {
    e?.stopPropagation();
    const res = await deleteInterfaceInfoUsingPost(record);
    if (res.code === 0) {
      message.success('删除成功');
    } else {
      message.error('删除失败');
    }
  };

  const handleUp = async (e: React.MouseEvent, record: API.IdRequest) => {
    e?.stopPropagation();
    const res = await interfaceUpUsingPost({id:record.id});
    if (res.code === 0) {
      message.success('发布成功');
    } else {
      message.error('发布失败');
    }
  };

  const handleDown = async (e: React.MouseEvent, record: API.IdRequest) => {
    e?.stopPropagation();
    const res = await interfaceDownUsingPost({id:record.id});
    if (res.code === 0) {
      message.success('下线成功');
    } else {
      message.error('下线失败');
    }
  };


  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const [messageApi, contextHolder] = message.useMessage();
  const {run: delRun, loading} = useRequest(removeRule, {
    manual: true,
    onSuccess: () => {
      setSelectedRows([]);
      actionRef.current?.reloadAndRest?.();
      messageApi.success('Deleted successfully and will refresh soon');
    },
    onError: () => {
      messageApi.error('Delete failed, please try again');
    },
  });
  const columns: ProColumns<API.InterfaceInfo>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'index'
    },
    {
      title: '接口名称',
      dataIndex: 'name',
      valueType: 'text',
      formItemProps: {
        rules: [{
          required: true
        }]
      }
    },
    {
      title: '描述',
      dataIndex: 'description',
      valueType: 'textarea'
    },
    {
      title: '请求方法',
      dataIndex: 'method',
      valueType: 'text'
    },
    {
      title: '请求参数',
      dataIndex: 'requestParams',
      valueType: 'jsonCode'
    },
    {
      title: 'url',
      dataIndex: 'url',
      valueType: 'text'
    },
    {
      title: '请求头',
      dataIndex: 'requestHeader',
      valueType: 'jsonCode',
    },
    {
      title: '响应头',
      dataIndex: 'responseHeader',
      valueType: 'jsonCode',
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '关闭',
          status: 'Default',
        },
        1: {
          text: '开启',
          status: 'Processing',
        },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInForm: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        // <UpdateForm
        //   trigger={<a>修改</a>}
        //   key="config"
        //   onOk={actionRef.current?.reload}
        //   values={record}
        // />
        <Button
          type="primary"
          key="primary"
          onClick={() => {
            handleUpdateModalOpen(true);
            setCurrentRow(record)
          }}
        >
          修改
        </Button>,
        // <Button
        //   type="primary"
        //   key="primary"
        //   onClick={()=>{
        //     deleteInterfaceInfoUsingPost(record);
        //   }}
        // >
        //   删除
        // </Button>
        record.status === 0 ?
        <Popconfirm
          title="发布"
          description="确定发布该接口吗"
          icon={<QuestionCircleOutlined style={{color: 'red'}}/>}
          onConfirm={(e) => {
            handleUp(e, record)
          }}
          okText="Yes"
          cancelText="No"
        >
          <Button type="primary"
                  key="online">发布</Button>
        </Popconfirm>
        :

        <Popconfirm
          title="下线"
          description="确定下线该接口吗"
          icon={<QuestionCircleOutlined style={{color: 'red'}}/>}
          onConfirm={(e) => {
            handleDown(e, record)
          }}
          okText="Yes"
          cancelText="No"
        >
          <Button type="primary"
                  key="ofline">下线</Button>
        </Popconfirm>
          ,
        <Popconfirm
          title="删除"
          description="确定删除该条记录吗"
          icon={<QuestionCircleOutlined style={{color: 'red'}}/>}
          onConfirm={(e) => {
            handleDelete(e, record)
          }}
          okText="Yes"
          cancelText="No"
        >
          <Button danger>删除</Button>
        </Popconfirm>



      ],
    },
  ];

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = useCallback(
    async (selectedRows: API.RuleListItem[]) => {
      if (!selectedRows?.length) {
        messageApi.warning('请选择删除项');
        return;
      }
      await delRun({
        data: {
          key: selectedRows.map((row) => row.key),
        },
      });
    },
    [delRun, messageApi.warning],
  );
  return (
    <PageContainer>
      {contextHolder}
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        // toolBarRender={() => [<CreateForm key="create" reload={actionRef.current?.reload} />]}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            新建
          </Button>
        ]}
        /*此处就是请求接口的位置*/
        request={async (params, sort: Record<string, SortOrder>, filter: Record<string, React.ReactText[] | null>) => {
          const res: any = await listInterfaceInfoByPageUsingPost({
            ...params
          })
          if (res?.data) {
            return {
              data: res?.data.records || [],
              success: true,
              total: res.data.total,
            }
          } else {
            return {
              data: [],
              success: false,
              total: 0
            }
          }
        }}

        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
              <span>
                服务调用次数总计{' '}
                {selectedRowsState.reduce((pre, item) => pre + (item.callNo ?? 0), 0)} 万
              </span>
            </div>
          }
        >
          <Button
            loading={loading}
            onClick={() => {
              handleRemove(selectedRowsState);
            }}
          >
            批量删除
          </Button>
          <Button type="primary">批量审批</Button>
        </FooterToolbar>
      )}

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
      {/* 创建一个CreateModal组件，用于在点击新增按钮时弹出 */}
      <CreateModal
        columns={columns}
        // 当取消按钮被点击时,设置更新模态框为false以隐藏模态窗口
        onCancel={() => {
          handleModalOpen(false);
        }}
        // 当用户点击提交按钮之后，调用handleAdd函数处理提交的数据，去请求后端添加数据(这里的报错不用管,可能里面组件的属性和外层的不一致)
        onSubmit={(values) => {
          handleAdd(values);
        }}
        // 根据更新窗口的值决定模态窗口是否显示
        visible={createModalOpen}
      />

      <UpdateModal
        columns={columns}
        onSubmit={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current?.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalOpen(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        visible={updateModalOpen}
        values={currentRow || {}}
      />

    </PageContainer>
  );
};
export default TableList;
